function theOrderOf(ribbons) {
    var getDirection = (d) => {
        var arr = ribbons.split('\n');
        for (x of arr) {
            if (x.indexOf(d) != x.lastIndexOf(d)) return 'horizontal'
        }
        return 'vertical'
    }
    var digits = Array.from({ length: 10 }, (_, i) => 0);
    for (x of ribbons) {
        if (/\d/.test(x)) digits[+x] += 1;
    }
    digits = digits.map((v, i) => [i, v]).filter(v => v[1] > 0).map(v => [v[0], v[1], getDirection(v[0])]).sort((a, b) => b[1] - a[1]).filter(v => v[1] > 0);
    var last = digits[0][0];
    var direction = getDirection(last);
    var horizontals = digits.filter(v => v[2] === 'horizontal');
    var verticals = digits.filter(v => v[2] === 'vertical');
    var result = ''
    if (direction === 'vertical') {
        while (verticals.length || horizontals.length) {
            if (verticals.length) result += verticals.shift()[0];
            if (horizontals.length) result += horizontals.shift()[0];

        }
    } else {
        while (verticals.length || horizontals.length) {
            if (horizontals.length) result += horizontals.shift()[0];
            if (verticals.length) result += verticals.shift()[0];
        }
    }
    return [...result].reverse().join('');
}
